package com.example.blog.util;



import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.*;


public class JwtHelper{
	/**
	 * 秘钥
	 */
	static final String SECRET = "cloud-Auth-Token";
	/**
	 * 签名是有谁生成
	 */
	static final String IS_SUS_ER = "Auth";
	/**
	 * 签名的主题
	 */
	static final String SUBJECT = "this is cloud token";
	/**
	 * 签名的观众
	 */
	static final String AUDIENCE = "Auth";


	public String createToken(String userId){
		try {
		    Algorithm algorithm = Algorithm.HMAC256(SECRET);
		    Map<String, Object> map = new HashMap<String, Object>(16);
		    Date nowDate = new Date();
		    // 过期时间：2小时
		    Date expireDate = getAfterDate(nowDate,0,0,0,2,0,0);
	        map.put("alg", "HS256");
	        map.put("typ", "JWT");
		    String token = JWT.create()
		    	// 设置头部信息 Header
		    	.withHeader(map)
		    	// 设置 载荷 Payload
		    	.withClaim("userId", userId)
		        .withIssuer(IS_SUS_ER)
		        .withSubject(SUBJECT)
		        .withAudience(AUDIENCE)
		        // 生成签名的时间
		        .withIssuedAt(nowDate)
		        // 签名过期的时间
		        .withExpiresAt(expireDate)
		        // 签名 Signature
		        .sign(algorithm);
		    return token;
		} catch (JWTCreationException exception){
			exception.printStackTrace();
		}
		return null;
	}

	public String verifyTokenAndGetUserId(String token) {
		Algorithm algorithm;
		try {
		    algorithm = Algorithm.HMAC256(SECRET);
		    JWTVerifier verifier = JWT.require(algorithm)
		        .withIssuer(IS_SUS_ER)
		        .build();
		    DecodedJWT jwt = verifier.verify(token);
		    Map<String, Claim> claims = jwt.getClaims();
		    Claim claim = claims.get("userId");
		    if (claim.asString() == null) {
				JWT.decode(token).getClaims();
			}
		    return claim.asString();
		} catch (JWTVerificationException exception){
			DecodedJWT decode = JWT.decode(token);
			/**
			 * jwt的头部
			 */
			String header = decode.getHeader();
			/**
			 * jwt的载荷
			 */
			String payload = decode.getPayload();
			/**
			 * jwt的签名
			 */
			String signature = decode.getSignature();
			/**
			 * 对头部和载荷进行签名
			 */
			String signature1 = getSignature(header, payload);
			/**
			 * 校验输入签名和生成的签名的一致性
			 */
			if (!signature1.equals("0")) {
				if (signature.equals(signature1)) {
					Map<String, Claim> claims = JWT.decode(token).getClaims();
					Claim claim = claims.get("userId");
					return claim.asString();
				}
				return "0";
			}
			return "0";
		}
	}

	private static String getSignature(String header, String payload) {
		try {
			String message = header+"."+payload;
			Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
			SecretKeySpec secret_key = new SecretKeySpec(SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
			sha256_HMAC.init(secret_key);
			byte[] bytes = sha256_HMAC.doFinal(message.getBytes(StandardCharsets.UTF_8));
			return extracted(bytes);
		} catch (Exception e) {
			return "0";
		}
	}

	private static String extracted(byte[] bytes) {
		return Base64.encodeBase64URLSafeString(bytes);
	}
	public Date getAfterDate(Date date, int year, int month, int day, int hour, int minute, int second){
		if(date == null){
			date = new Date();
		}

		Calendar cal = new GregorianCalendar();

		cal.setTime(date);
		if(year != 0){
			cal.add(Calendar.YEAR, year);
		}
		if(month != 0){
			cal.add(Calendar.MONTH, month);
		}
		if(day != 0){
			cal.add(Calendar.DATE, day);
		}
		if(hour != 0){
			cal.add(Calendar.HOUR_OF_DAY, hour);
		}
		if(minute != 0){
			cal.add(Calendar.MINUTE, minute);
		}
		if(second != 0){
			cal.add(Calendar.SECOND, second);
		}
		return cal.getTime();
	}
}
